import { Vue, Component, Prop, Provide, Emit, Watch } from 'vue-property-decorator';
import { Subject } from 'rxjs';
import { CreateElement } from 'vue';
import './uni-res-mpickup-view.less';

import MPickupViewEngine from '@engine/view/mpickup-view-engine';

import view_pickupviewpanel from '@widget/uni-res/mpickup-viewpickupviewpanel-pickupviewpanel/mpickup-viewpickupviewpanel-pickupviewpanel';

@Component({
    components: {
        view_pickupviewpanel, 
    },
    beforeRouteEnter: (to: any, from: any, next: any) => {
        next((vm: any) => {
            vm.$store.commit('addCurPageViewtag', { fullPath: to.fullPath, viewtag: vm.viewtag });
        });
    },
})
export default class UniResMPickupView extends Vue {

    /**
     * 数据变化
     *
     * @param {*} val
     * @returns {*}
     * @memberof UniResMPickupView
     */
    @Emit() 
    public viewDatasChange(val: any):any {
        return val;
    }

    /**
     * 数据视图
     *
     * @type {string}
     * @memberof UniResMPickupView
     */
    @Prop() public viewdata!: string;

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof AppDashboardView
	 */
	public viewtag: string = '2242065285c5ca1b9e276536342bfb68';

    /**
     * 父数据对象
     *
     * @protected
     * @type {*}
     * @memberof UniResMPickupView
     */
    protected srfparentdata: any = {};

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof UniResMPickupView
     */
    public model: any = {
        srfTitle: '统一资源实体数据多项选择视图',
        srfCaption: 'unires.views.mpickupview.caption',
        srfSubCaption: '',
        dataInfo: ''
    }

    /**
     * 处理值变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof UniResMPickupView
     */
    @Watch('viewdata')
    onViewData(newVal: any, oldVal: any) {
        const _this: any = this;
        if (!Object.is(newVal, oldVal) && _this.engine) {
            _this.engine.setViewData(newVal);
            _this.engine.load();
        }
    }

    /**
     * 容器模型
     *
     * @type {*}
     * @memberof UniResMPickupView
     */
    public containerModel: any = {
        view_pickupviewpanel: { name: 'pickupviewpanel', type: 'PICKUPVIEWPANEL' },
        view_okbtn: { name: 'okbtn', type: 'button', text: '确定', disabled: true },
        view_cancelbtn: { name: 'cancelbtn', type: 'button', text: '取消', disabled: false },
        view_leftbtn: { name: 'leftbtn', type: 'button', text: '左移', disabled: true },
        view_rightbtn: { name: 'rightbtn', type: 'button', text: '右移', disabled: true },
        view_allleftbtn: { name: 'allleftbtn', type: 'button', text: '全部左移', disabled: true },
        view_allrightbtn: { name: 'allrightbtn', type: 'button', text: '全部右移', disabled: true },
    };

    /**
     * 视图状态订阅对象
     *
     * @private
     * @type {Subject<{action: string, data: any}>}
     * @memberof UniResMPickupView
     */
    public viewState: Subject<ViewState> = new Subject();

    /**
     * 视图引擎
     *
     * @private
     * @type {Engine}
     * @memberof UniResMPickupView
     */
    private engine: MPickupViewEngine = new MPickupViewEngine();

    /**
     * 引擎初始化
     *
     * @private
     * @memberof UniResMPickupView
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            pickupviewpanel: this.$refs.pickupviewpanel,
            isLoadDefault: true,
        });
    }

    /**
     * Vue声明周期
     *
     * @memberof UniResMPickupView
     */
    public created() {
        const secondtag = this.$util.createUUID();
        this.$store.commit('viewaction/createdView', { viewtag: this.viewtag, secondtag: secondtag });
        this.viewtag = secondtag;
        
    }

    /**
     * 销毁之前
     *
     * @memberof UniResMPickupView
     */
    public beforeDestroy() {
        this.$store.commit('viewaction/removeView', this.viewtag);
    }

    /**
     * Vue声明周期(组件初始化完毕)
     *
     * @memberof UniResMPickupView
     */
    public mounted() {
        const _this: any = this;
        _this.engineInit();
        if (_this.loadModel && _this.loadModel instanceof Function) {
            _this.loadModel();
        }
        
    }


    /**
     * pickupviewpanel 部件 selectionchange 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof UniResMPickupView
     */
    public pickupviewpanel_selectionchange($event: any, $event2?: any) {
        this.engine.onCtrlEvent('pickupviewpanel', 'selectionchange', $event);
    }


    /**
     * pickupviewpanel 部件 activated 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof UniResMPickupView
     */
    public pickupviewpanel_activated($event: any, $event2?: any) {
        this.engine.onCtrlEvent('pickupviewpanel', 'activated', $event);
    }


    /**
     * pickupviewpanel 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof UniResMPickupView
     */
    public pickupviewpanel_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('pickupviewpanel', 'load', $event);
    }




    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof UniResMPickupView
     */
    public closeView(args: any[]): void {
        let _view: any = this;
        if (_view.viewdata) {
            _view.$emit('viewdataschange', args);
            _view.$emit('close');
        } else if (_view.$tabPageExp) {
            _view.$tabPageExp.onClose(_view.$route.fullPath);
        }
    }

    /**
     * 视图选中数据
     *
     * @type {any[]}
     * @memberof UniResMPickupView
     */
    public viewSelections:any[] = [];

    /**
     * 是否单选
     *
     * @type {boolean}
     * @memberof UniResMPickupView
     */
    public isSingleSelect: boolean = false;

    /**
     * 选中数据单击
     *
     * @param {*} item
     * @memberof UniResMPickupView
     */
    public selectionsClick(item:any):void {
        item._select = !item._select;
        const removeSelect: boolean = this.viewSelections.some((selection: any) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
    }

    /**
     * 选中树双击
     *
     * @param {*} item
     * @memberof UniResMPickupView
     */
    public selectionsDBLClick(item:any):void {
        const index: number = this.viewSelections.findIndex((selection: any) => Object.is(selection.srfkey, item.srfkey));
        if (index !== -1) {
            this.viewSelections.splice(index, 1);
        }
        const removeSelect: boolean = this.viewSelections.some((selection: any) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
    }

    /**
     * 删除右侧全部选中数据
     *
     * @memberof UniResMPickupView
     */
    public onCLickLeft():void {
        const _selectiions = [...JSON.parse(JSON.stringify(this.viewSelections))];
        _selectiions.forEach((item: any) => {
            if (!item._select) {
                return;
            }
            const index = this.viewSelections.findIndex((selection: any) => Object.is(item.srfkey, selection.srfkey));
            if (index !== -1) {
                this.viewSelections.splice(index, 1);
            }
        });
        const removeSelect: boolean = this.viewSelections.some((selection: any) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
    }

    /**
     * 添加左侧选中数据
     *
     * @memberof UniResMPickupView
     */
    public onCLickRight():void {
        Object.values(this.containerModel).forEach((model: any) => {
            if (!Object.is(model.type, 'PICKUPVIEWPANEL')) {
                return;
            }
            model.selections.forEach((item: any) => {
                const index: number = this.viewSelections.findIndex((selection: any) => Object.is(item.srfkey, selection.srfkey));
                if (index === -1) {
                    let _item: any = { ...JSON.parse(JSON.stringify(item)) };
                    Object.assign(_item, { _select: false })
                    this.viewSelections.push(_item);
                }
            });
        });
    }

    /**
     * 选中数据全部删除
     *
     * @memberof UniResMPickupView
     */
    public onCLickAllLeft():void {
        this.viewSelections = [];
        this.containerModel.view_leftbtn.disabled = true;
    }

    /**
     * 添加左侧面板所有数据到右侧
     *
     * @memberof UniResMPickupView
     */
    public onCLickAllRight():void {
        Object.values(this.containerModel).forEach((model: any) => {
            if (!Object.is(model.type, 'PICKUPVIEWPANEL')) {
                return;
            }
            model.datas.forEach((item: any) => {
                const index: number = this.viewSelections.findIndex((selection: any) => Object.is(item.srfkey, selection.srfkey));
                if (index === -1) {
                    let _item: any = { ...JSON.parse(JSON.stringify(item)) };
                    Object.assign(_item, { _select: false })
                    this.viewSelections.push(_item);
                }
            });
        });
    }

    /**
     * 确定
     *
     * @memberof UniResMPickupView
     */
    public onClickOk(): void {
        this.$emit('viewdataschange', this.viewSelections);
        this.$emit('close', null);
    }

    /**
     * 取消
     *
     * @memberof UniResMPickupView
     */
    public onClickCancel(): void {
        this.$emit('close', null);
    }


    /**
     * 绘制视图消息 （上方）
     *
     * @returns
     * @memberof UniResMPickupView
     */
    public renderPosTopMsgs() {
        return (
            <div class='view-top-messages'>
            </div>
        );
    }

    /**
     * 绘制视图消息 （下方）
     *
     * @returns
     * @memberof UniResMPickupView
     */
    public renderPosBottomMsgs() {
        return (
            <div class='view-bottom-messages'>
            </div>
        );
    }
    
    /**
     * 绘制内容
     *
     * @param {CreateElement} h
     * @returns
     * @memberof UniResMPickupView
     */
    public render(h: CreateElement) {
        return (
        <div class="view-container uni-res-mpickup-view">
            <card class='view-card' dis-hover={true} padding={0} bordered={false}>
                <div class="content-container pickup-view">
               
                    <div class="translate-contant">
                        <div class="center">
                            <view_pickupviewpanel 
            viewState={this.viewState} 
                isSingleSelect={this.isSingleSelect}
         
            name='pickupviewpanel' 
            ref='pickupviewpanel' 
            on-selectionchange={($event: any) => this.pickupviewpanel_selectionchange($event)} 
            on-activated={($event: any) => this.pickupviewpanel_activated($event)} 
            on-load={($event: any) => this.pickupviewpanel_load($event)} 
            on-closeview={($event: any) => this.closeView($event)}>
        </view_pickupviewpanel>
                        </div>
                        <div class="translate-buttons">
                            <div class="buttons">
                                <i-button type="primary" title={this.containerModel.view_rightbtn.text}
                                    disabled={this.containerModel.view_rightbtn.disabled}
                                    on-click={() => this.onCLickRight()}>
                                    <i class="el-icon-arrow-right"></i>
                                </i-button>
                                <i-button type="primary" title={this.containerModel.view_leftbtn.text}
                                    disabled={this.containerModel.view_leftbtn.disabled}
                                    on-click={() => this.onCLickLeft()}>
                                    <i class="el-icon-arrow-left"></i>
                                </i-button>
                                <i-button type="primary" title={this.containerModel.view_allrightbtn.text}
                                    on-click={() => this.onCLickAllRight()}>
                                    <i class="el-icon-d-arrow-right"></i>
                                </i-button>
                                <i-button type="primary" title={this.containerModel.view_allleftbtn.text}
                                    on-click={() => this.onCLickAllLeft()}>
                                    <i class="el-icon-d-arrow-left"></i>
                                </i-button>
        
                            </div>
                        </div>
                        <div class="right">
                            <div class="mpicker-select">
                                {
                                    this.viewSelections.map((item: any) => {
                                        return (
                                            <div class={item._select ? 'select' : ''}
                                                on-click={() => this.selectionsClick(item)}
                                                on-dblclick={() => this.selectionsDBLClick(item)}>
                                                <span>{item.srfmajortext}</span>
                                            </div>
                                        );
                                    })
                                }
                            </div>
                        </div>
                    </div>
        
                     <card dis-hover={true} bordered={false} class="footer">
                        <row style={{ textAlign: 'right' }}>
                            <i-button type="primary"  disabled={this.viewSelections.length > 0 ? false : true} 
                                    on-click={() => this.onClickOk()}>{this.containerModel.view_okbtn.text}</i-button>
                                    &nbsp;&nbsp;
                            <i-button on-click={() => this.onClickCancel()}>{this.containerModel.view_cancelbtn.text}</i-button>
                        </row>
                    </card>
                </div>
            </card>
        </div>
        );
    }

}